<?php

namespace App\Models\CacheModel\privatearea;

use app\common\lib\Aes;
use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class PrivateAreaMallGoods extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_mall_goods';

    protected $cacheModel = 'privatearea.mall_good';

    /**
     * 获取商品列表
     * @param int $page
     * @param int $pageSize
     * @param array $fields
     * @return array
     * @throws \Exception
     */
    public function getGoodList(int $page = 1, int $pageSize = 20, array $fields = [])
    {
        $data = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel)
            ->setPage($page)
            ->setPageSize($pageSize)
            ->setSort('desc')
            ->setListKeyType(0)
            ->getListPageDataIds(function ($ids = [], $isCache = true, $sortType = 'desc')
            {
                try
                {
                    $data = $this->alias('g')->join('wechat_backup_07_18_14_43_00.private_area_mall_goods_type t', 'g.tid = t.id')->where(['g.status' => 1, 't.status' => 1])->order('g.sort desc,g.id desc')->column('g.sort', 'g.id');
                    $resData = [];
                    foreach ($data as $id => $sort)
                    {
                        $resData[$id] = ['id' => $id, 'sort' => $sort,];
                    }
                    return $resData;
                }
                catch (\Exception $e)
                {
                    $data = [];
                }
                return $data;
            }, 'sort');

        $dataLiist = $this->batchGetInfoByIds(array_keys($data['data']), $fields);
        $resDataList = [];
        foreach ($data['data'] as $id => $sort)
        {
            if (isset($dataLiist[$id]))
            {
                $resDataList[] = $dataLiist[$id];
            }
        }
        $data['data'] = $resDataList;
        return $data;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            // 获取未删除 的数据
            $data = $this
                ->where(['id' => ['in', $ids]])
                ->column('id,status,sort,tid,cid,is_recommend,has_quality_check,name,img,content,create_time,update_time', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'status', 'is_recommend', 'has_quality_check', 'sort', 'cid', 'tid', 'create_time', 'update_time']);
        }
        return $data;
    }

    /**
     * 获取商品列表数据
     * @param array $data
     * @param array $gData
     * @return array
     * @throws \Exception
     */
    public function pageDataResert(array $data, array $gData)
    {
        $resData = [];
        $privateAreaMallGoodsAttrModel = new PrivateAreaMallGoodsAttr();
        $aesModel = new Aes();
        foreach ($data as $itemData)
        {   // 没有规格 的 不显示
            $goodAttrInfo = $privateAreaMallGoodsAttrModel->getGoodAttrList($itemData['id'], 1, 1);
            if (empty($goodAttrInfo['data']))
            {
                continue;
            }
            $currGoodAttr = current($goodAttrInfo['data']);
            $idData = ['gid' => $itemData['id'], 'end_time' => $gData['end_time'], 'hash' => $gData['hash']];
            $resData[] = [
                'sn' => urlencode($aesModel->encryptWithOpenssl(json_encode($idData, JSON_UNESCAPED_UNICODE), 'privatearea_mall')),
                'img' => $itemData['img'],
                'title' => $itemData['name'],
                'tip' => $itemData['is_recommend'] ? '推荐' : '',
                'old_price' => (float)$currGoodAttr['or_price'],
                'new_price' => (float)$currGoodAttr['now_price'],
            ];
        }
        return $resData;
    }

    /**
     * 获取商品详情信息
     * @param int $gid
     * @param int $endTime
     * @return array
     * @throws \Exception
     */
    public function getGoodDetail(int $gid, int $endTime = 0)
    {   // 获取商品详情
        $goodInfo = $this->getInfoById($gid);
        // 获取商品规格列表
        $privateAreaMallGoodsAttrModel = new PrivateAreaMallGoodsAttr();
        $goodAttrData = $privateAreaMallGoodsAttrModel->getGoodAttrList($gid, -1, 20);
        $nowTime = time();
        $imgs = $goodInfo['img'] ? [$goodInfo['img']] : [];
        $specificationsList = [];
        $n = count($imgs);
        $oldPrice = 0;
        $newPrice = 0;
        $totalInventory = 0;
        $status = 1;
        $remainingTime = 0;
        if ($endTime > 0)
        {   // 上架计时
            $remainingTime = $endTime - $nowTime;
            if ($remainingTime < 0)
            {   // 已下架
                $status = 2;
            }
        }
        if ($goodInfo['status'] !== 1)
        {   // 已下架
            $status = 2;
        }
        foreach ($goodAttrData['data'] as $i => $datum)
        {
            $imgs[] = $datum['img'];

            $specificationsList[] = [
                'name' => $datum['name'],
                'old_price' => (float)$datum['or_price'],
                'new_price' => (float)$datum['now_price'],
                'stock_num' => $datum['inventory'],
                'img_index' => $i + $n,
                'sid' => $datum['id'],
            ];
            if (!$oldPrice && !$newPrice && $datum['inventory'])
            {
                $oldPrice = (float)$datum['or_price'];
                $newPrice = (float)$datum['now_price'];
            }
            $totalInventory += $datum['inventory'];
        }
        if ($status === 1 && !$totalInventory)
        {   // 已售空
            $status = 3;
        }
        if (!$oldPrice && !$newPrice)
        {
            if (!empty($specificationsList))
            {
                $oldPrice = $specificationsList[0]['old_price'];
                $newPrice = $specificationsList[0]['new_price'];
            }
        }
        if ($status === 1)
        {   // 商品状态为上架
            // 获取商品 分类信息
            $goodTypeStatus = (new PrivateAreaMallGoodsType())->where('id', $goodInfo['tid'])->value('status');
            // 商品类型状态（0 =>下架,1=>上架）
            $goodTypeStatus = (int)$goodTypeStatus;
            if (!$goodTypeStatus)
            {
                $status = 2;    //  1=>正常 2=>已下架 3=>已售空
            }
        }
        return [
            'imgs' => $imgs,
            'title' => $goodInfo['name'],
            'old_price' => $oldPrice,
            'new_price' => $newPrice,
            'specifications_list' => $specificationsList,
            'good_intro' => $goodInfo['content'],
            'status' => $status,
            'remaining_time' => max($remainingTime, 0),
        ];
    }
}
